<template>
  <el-upload class="avatar-uploader" :action="action" :show-file-list="false" :auto-upload="false"
    :on-change="handleChange" :before-upload="beforeUpload">
    <el-image v-if="imageUrl" :src="imageUrl" class="avatar" fit="cover" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>
<script lang="ts" setup>
import app from "@/constants/app";
import { getCache, getToken } from "@/utils/cache";
import { ElMessage, UploadProps } from "element-plus";
import { computed, ref, toRef } from "vue";
import axios from "axios";
import { CacheTenantCode } from "@/constants/cacheKey";

const props = defineProps({
  modelValue: String,
  imagePath: String,
});

const imageUrl = toRef(props, 'modelValue');

const emit = defineEmits(["update:modelValue", "update:imagePath"]);

const action = `${app.api}/sys/oss/upload?token=Bearer ${getToken()}`;

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  var fileType = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  if (!['png', 'jpg', 'JPG', 'jepg'].includes(fileType)) {
    ElMessage.error({
      message: '图片格式错误!',
    });
    return;
  }
};

const handleChange: UploadProps['onChange'] = (rawFile) => {
  if (rawFile.raw) {
    const formData = new FormData();
    formData.append('file', rawFile.raw);
    let headers = {} as any;
    if (app.tenantMode === "code") {
      headers.tenantCode = getCache(CacheTenantCode, { isParse: false }) || "";
    }
    axios({
      url: `${app.api}/data/api/upload`,
      data: formData,
      method: 'post',
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data',
        authorization: `Bearer ${getToken()}`,
      }
    }).then(({ data }) => {
      if (data.code !== 0) {
        ElMessage.error({
          message: '上传失败',
        });
      } else {
        ElMessage.success({
          message: data.msg || '上传成功',
        });
        imageUrl.value = data.data.imageUrl;
        emit("update:modelValue", data.data.imageUrl);
        emit("update:imagePath", data.data.localPath);
      }
    });
  }
};
</script>

<style>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>